package com.netmarch.jt809.server;

import com.netmarch.jt809.bean.Message;
import com.netmarch.jt809.server.bean.Container;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Decoder extends FrameDecoder {

    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {

        int head = buffer.getByte(0);
        int tail = buffer.getByte(buffer.capacity() - 1);
        /*System.out.println("[" + buffer.getByte(0) + "," + buffer.getByte(buffer.capacity() - 1) + "]");
        if (!(head == Message.MSG_HEAD && tail == Message.MSG_TALL)) {
            return null;
        }*/
        for (int i = 0; i <= buffer.capacity() - 1; i++) {
            if (buffer.getByte(i) != (0x5b)) {
                buffer.skipBytes(1);
            } else {
                break;
            }
        }
        //跳过头标识
        buffer.skipBytes(1);
        //读取报文长度（目前有不一致情况）
        Message msg = this.buildMessage(buffer);
        return msg;
    }

    /**
     * 报文转义 * void * @param bytes * @param formatBuffer
     */
    public static byte[] formatByte(List<Byte> bytes, byte[] bytesnew) {
        int a = 0;
        for (int i = 0; i < bytes.size(); i++)
            if (i != bytes.size() - 1 && bytes.get(i) == 0x5a && bytes.get(i + 1) == 0x01) {
                bytesnew[a++] = (0x5b);
                i++;
            } else if (i != bytes.size() - 1 && bytes.get(i) == 0x5a && bytes.get(i + 1) == 0x02) {
                bytesnew[a++] = (0x5a);
                i++;
            } else if (i != bytes.size() - 1 && bytes.get(i) == 0x5e && bytes.get(i + 1) == 0x01) {
                bytesnew[a++] = (0x5d);
                i++;
            } else if (i != bytes.size() - 1 && bytes.get(i) == 0x5e && bytes.get(i + 1) == 0x02) {
                bytesnew[a++] = (0x5e);
                i++;
            } else {
                bytesnew[a++] = (bytes.get(i));
            }
        return bytesnew;
    }

    public static int formatBuffernum(byte[] bytes) {
        int a = 0;
        for (int i = 0; i < bytes.length; i++) {
            if (i != bytes.length - 1 && bytes[i] == 0x5a && bytes[i + 1] == 0x01) {
                a++;
            } else if (i != bytes.length - 1 && bytes[i] == 0x5a && bytes[i + 1] == 0x02) {
                a++;
            } else if (i != bytes.length - 1 && bytes[i] == 0x5e && bytes[i + 1] == 0x01) {
                a++;
            } else if (i != bytes.length - 1 && bytes[i] == 0x5e && bytes[i + 1] == 0x02) {
                a++;
            }
        }
        return a;
    }

    public static int skipIF(int start, int num, ChannelBuffer buffer) {
        for (int i = 0; i < num; i++) {
            if (buffer.getByte(start) == 0x5a || buffer.getByte(start) == 0x5e) {
                buffer.skipBytes(1);//1 byte
                start++;
            }
            start++;
        }
        return start;
    }


    private Message buildMessage(ChannelBuffer headFormatedBuffer) {
        Message msg = new Message();
        int start = 1;
        for (int i = 0; i <= headFormatedBuffer.capacity() - 1; i++) {
            if (headFormatedBuffer.getByte(i) != (0x5b)) {
                start++;
            } else {
                break;
            }
        }
        //读取报文长度（目前有不一致情况）
        msg.setMsgLength(headFormatedBuffer.readUnsignedInt());
        start = skipIF(start, 4, headFormatedBuffer);
        msg.setMsgSn(headFormatedBuffer.readInt());//4 byte
        start = skipIF(start, 4, headFormatedBuffer);
        msg.setMsgId(headFormatedBuffer.readUnsignedShort());//2 byte
        start = skipIF(start, 2, headFormatedBuffer);
        msg.setMsgGesscenterId(headFormatedBuffer.readUnsignedInt());//4 byte
        start = skipIF(start, 4, headFormatedBuffer);
        msg.setVersionFlag(headFormatedBuffer.readBytes(3).array());//3 byte
        start = skipIF(start, 3, headFormatedBuffer);
        msg.setEncryptFlag(headFormatedBuffer.readUnsignedByte());//1 byte
        start = skipIF(start, 1, headFormatedBuffer);
        msg.setEncryptKey(headFormatedBuffer.readUnsignedInt());//4 byte
        start = skipIF(start, 4, headFormatedBuffer);
        ChannelBuffer bodyBytes = headFormatedBuffer.readBytes(headFormatedBuffer.readableBytes() - 2 - 1);//数据体为变长字节
        msg.setMsgBody(bodyBytes);
        msg.setCrcCode(headFormatedBuffer.readUnsignedShort());//2 byte
        //跳过尾标识
        headFormatedBuffer.skipBytes(1);//1 byte
        //buffer.readByte();

        msg.setContentList(getArrays(headFormatedBuffer));
        System.out.println(msg.getContentList().size());
        System.out.println("after build message readable bytes:" + headFormatedBuffer.readableBytes());
        return msg;
    }

    public static List<byte[]> getArrays(ChannelBuffer buffer) {
        List<byte[]> list = new ArrayList<>();
        List<List<Byte>> temp = new ArrayList<>();
        List<Byte> temparr = new ArrayList();
        for (int i = 0; i <= buffer.capacity() - 1; i++) {
            if (buffer.getByte(i) == (0x5d)) {
                temparr.add(buffer.getByte(i));
                temp.add(temparr);
                temparr = new ArrayList();
            } else {
                temparr.add(buffer.getByte(i));
            }
        }
        for (List<Byte> beanlist : temp) {
            byte[] arr = new byte[200];
            list.add(formatByte(beanlist, arr));
        }
        return list;
    }

}
